// var host = 'http://192.168.1.105:8080/'
var host = 'http://192.168.1.115:8080/'
// var host = 'http://192.168.0.45:8080/'
// var host = 'http://192.168.43.79:8080/'
// var host = 'http://106.15.130.16:8787/'


// var host = 'http://47.101.30.145:8787/'

// var host = 'http://192.168.2.5:8080/'

import utils from '../utils/utils.js'

var isLoginPage = false

// let navigator=weex.requireModule('navigator')


export default {

    postShort: function (weg, param, header, start, success, compelete) {
        var modal = weex.requireModule("modal")
        this.postFull(weg, param, header, start, success, function (res) {
            //fail
            modal.toast({message: res.msg})
        }, function () {
            //exception
            modal.toast({message: '网络异常！'})
        }, function () {
            //compelete

            compelete();
        })

    },

    postFull: function (weg, param, header, start, success, fail, exception, compelete) {
        var net = weex.requireModule("net")
        var modal = weex.requireModule("modal")
        var md5 = require('md5')
        var base64 = require('base64-encoder').Base64
        var pref = weex.requireModule("pref")


        var self = this
        var url = host + weg

        //设置传参格式
        var paramData = new Object()

        var sid = pref.getString('sid')
        if (sid != undefined && sid != null && sid != '') {
            paramData.sid = sid
        }

        if (weex.config.env.platform == 'android') {
            paramData.deviceType = '1000'
        } else if (weex.config.env.platform == 'ios') {
            paramData.deviceType = '1100'
        } else if (weex.config.env.platform == 'web') {
            paramData.deviceType = '1300'
        }
        paramData.reqData = param

        var reqData = new Object()
        reqData.data = paramData

        var strMd = md5(JSON.stringify(paramData))

        reqData.signData = base64.encode(strMd)

        net.post(url, reqData, header, function () {
            //start
            start();
        }, function (e) {

            var res = e.res

            //fail
            if (res.status == 0) {
                modal.toast({message: e.res.msg})
                fail(res)

                //success
            } else if (res.status == 1) {
                success(e.res.data)

                //timeout
            } else if (res.status == 2) {
                var nav = weex.requireModule("navigator")
                nav.push('../login/login.js')
            }

        }, function (e) {
            //compelete
            compelete();
        }, function (e) {
            modal.toast({message: e})
            // exception
            exception();
        });

    },


    /**
     *
     * @param weg 请求地址
     * @param option {
     *      progress:是否显示进度条，默认true 显示
     *      data:请求的数据，数据必须是一个对象或者null
     *      fail:失败的处理
     *      start:请求开始处理函数
     *      success:成功的处理函数
     *      fail:请求失败处理函数
     *      exception:异常函数
     *      compelete:完成函数
     *  }
     */
    postDefine: function (weg, option) {

        var modal = weex.requireModule("modal")
        var net = weex.requireModule("net")
        var md5 = require('md5')
        var base64 = require('base64-encoder').Base64
        var pref = weex.requireModule("pref")

        var param = option.data


        if (!weg) {
            modal.toast({message: '请求地址不能为空'})
            return
        }

        if (option.progress == undefined || option.progress == null) {
            option.progress = true
        }

        var self = this
        var url = host + weg


        //设置传参格式
        var paramData = new Object()

        var platform = weex.config.env.platform.toLowerCase()

        if (platform == 'android') {
            paramData.deviceType = '1000'
        } else if (platform == 'ios') {
            paramData.deviceType = '1100'
        } else if (platform == 'web') {
            paramData.deviceType = '1300'
        }

        if (!param) {
            param = {}
        }
        paramData.reqData = param

        //token
        // pref.setString('sid','')
        var sid = pref.getString('sid')
        if (sid != undefined && sid != null && sid != '') {
            paramData.sid = sid
        }
        var stringify = require('fast-json-stable-stringify');

        var reqData = new Object()
        utils.removeJsonNull(paramData)
        reqData.data = stringify(paramData)

        var strMd = md5(stringify(paramData))

        reqData.signData = base64.encode(strMd)

        var header = option.header
        if (!header) {
            header = {}
        }

        header['isWeex'] = 'true'

        //清除cooki
        net.removeAllCookies()


        // modal.alert({message:'-------------'})
        // return

        // navigator.presentFull({url:'root:com/yx/login/login.js',animated:false})
        // return

        net.post(url, reqData, header, function () {
            //start
            if (option.progress) {
                var progress = weex.requireModule("progress")
                progress.show()
            }

            if (typeof option.start === "function") {
                option.start()
            }

        }, function (e) {
            var modal = weex.requireModule("modal")


            var res = e.res

            //fail
            if (res.status == 0) {
                if (typeof option.fail === "function") {
                    option.fail(res)
                } else {
                    // modal.toast({message: res.msg})
                }

                //success
            } else if (res.status == 1) {
                if (typeof option.success === "function") {
                    option.success(res.data)
                }

                //timeout
            } else if (res.status == 2) {
                // var nav = weex.requireModule("navigator")

                if (isLoginPage) {
                    return
                }
                isLoginPage = true

                // modal.toast({message:19})

                let navigator=weex.requireModule('navigator')
                // navigator.present('root:com/yx/login/login.js')
                //
                // navigator.presentFull({url: 'root:com/yx/login/login.js'}, (e) => {
                navigator.pushFull({url: 'root:com/yx/login/login.js'}, (e) => {
                    let page = weex.requireModule("page")
                    page.reload()
                    isLoginPage = false
                })
            }

        }, function (e) {
            //compelete
            if (typeof option.compelete === "function") {
                option.compelete(e)
            }

            if (option.progress) {
                var progress = weex.requireModule("progress")
                progress.dismiss()
            }

        }, function (e) {
            var modal = weex.requireModule("modal")
            // exception
            if (typeof option.exception === "function") {
                option.exception(e)
            }
            // modal.toast({message: e})
        });

    },

    post: function (weg, param, success) {
        var progress = weex.requireModule("progress")
        this.postShort(weg, param, {}, function () {
            progress.show()
        }, success, function () {
            progress.dismiss()
        });
    },

    postSilent: function (weg, param, success) {

        this.postFull(weg, param, {}, function () {

        }, success, function (res) {
            //fail

        }, function () {
            //exception

        }, function () {
            //compelete


        })
    },

    /**
     * path 多个文件是一个数组
     * @param param
     * @param path
     * @param start
     * @param success
     * @param compelete
     * @param exception
     */
    postFile: function (path,option) {

        var modal = weex.requireModule("modal")
        var net = weex.requireModule("net")


        var files = {
            files: path
        }

        var url = host + 'app/file/newUploadFiles'

        /**
         * @param url 地址
         * @param param 参数
         * @param header header
         * @param path path
         * @param start 开始的回调
         * @param success status==200的回调
         * @param compelete 完成的回调，不论请求成功失败
         * @param exception status!=200的回调
         */

        net.postFile(url, {}, {}, files, () => {

            //start
            if (option.progress == null || option.progress == undefined || option.progress) {
                var progress = weex.requireModule('progress')
                progress.show()
            }

            if (typeof option.start === 'function') {
                option.start()
            }

        }, (e)=>{

            var res = JSON.parse(e.res)
            //fail
            if (res.status == 0) {
                if (typeof option.fail === 'function') {
                    option.fail(res)
                } else {
                    modal.toast({message: res.msg})
                }

                //success
            } else if (res.status == 1) {

                if (typeof option.success === 'function') {
                    option.success(res.data)
                }
            }


        }, (e)=>{
            //compelete
            if (typeof option.compelete === 'function') {
                option.compelete(e)
            }



            if (option.progress == null || option.progress == undefined || option.progress) {
                var progress = weex.requireModule('progress')
                progress.dismiss()
            }
        }, ()=>{
            // exception
            if (typeof option.exception === 'function') {
                option.exception(e)
            }
            modal.toast({message: e})
        })
    },

    //请求前缀地址
    host:host,
    postTest: function () {
        var stream = weex.requireModule('stream')
        var modal = weex.requireModule('modal')
        var reqData = {}
        reqData.data = {name:'小明',age:12}

        modal.alert({message:123})

        var header = {}

        // header['Accept'] = ' */*'
        // header['Accept-Encoding'] = 'gzip, deflate'
        // header['Accept-Language'] = 'zh-CN,zh;q=0.9'
        // header['Connection'] = 'keep-alive'
        // header['Content-Type'] = 'multipart/form-data; boundary=----WebKitFormBoundarymPMDgoq3kRHWkxPB'
        // header['Content-Type'] = 'multipart/form-data;'

        // header = {'Accept':'application/json'}
        header = {
            'Content-Type':'application/x-www-form-urlencoded',
            'isIos':'true'
        }

        var reqData = {"data":{"deviceType":"1000","reqData":{"loginCode":"yxq02","password":"19c73fd98fc57b83da400485e4f8df57"}},"signData":"OTg0Y2E4OUjODM0MmYzZDIxOWQzYWM4YzA5N2E4Mzl="}

        // modal.alert({message:JSON.stringify(reqData)})
        stream.fetch({
            headers:header,
            method:'POST',
            url: host+'app/system/user/login',
            type:'text',
            // body:{"deviceType":"1000","reqData":{"loginCode":"yxq02","password":"19c73fd98fc57b83da400485e4f8df57"}},
            // body:'{"data":{"deviceType":"1000","reqData":{"loginCode":"yxq02","password":"19c73fd98fc57b83da400485e4f8df57"}},"signData":"OTg0Y2E4OUjODM0MmYzZDIxOWQzYWM4YzA5N2E4Mzl="}'
            // body:{"data":{"deviceType":"1000","reqData":{"loginCode":"yxq02","password":"19c73fd98fc57b83da400485e4f8df57"}},"signData":"OTg0Y2E4OUjODM0MmYzZDIxOWQzYWM4YzA5N2E4Mzl="},
            body:JSON.stringify(reqData)
        }, function(ret) {
            if(!ret.ok){
                modal.alert({message:"request failed"})
            // }else{
            //     modal.alert({message:JSON.stringify(ret.data)})
            }
        },function(response){
            // modal.alert({message:"bytes received:"+response.length})
        });
    }
}
